import Vue from 'vue'
import VueRouter from 'vue-router'
import request from "@/utils/request";

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    component: () => import('../view/Login.vue'),
    meta: {
      keepAlive: true
    }
  },
  {
    path: '/admin/:uid/:page',
    component: () => import('../view/Admin.vue'),
    meta: {
      keepAlive: true,
      requireAuth:true
    }
  }
]

//可以重复跳转同一个url
// const originalPush = VueRouter.prototype.push
// VueRouter.prototype.push = function push(location) {
//   return originalPush.call(this, location).catch(err => err)
// }





const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})


router.beforeEach((to, from, next) => {
  if (to.meta.requireAuth) { // 判断该路由是否需要登录权限
    const user=localStorage.getItem('user')? JSON.parse(localStorage.getItem('user')):null
    if(user){ //判断本地是否存在access_token
      if(to.params.uid === user.id){
        next()
      }else{
        request.get("/room/"+to.params.uid).then(res=>{
          if(res){
            if(res.data.state === 1){
              next()
            }else{
              alert("对方没有开启协作")
              next({
                path:'/admin/'+user.id+'/'+1
              });
            }
          }else{
            alert("不知名问题")
            next({
              path:'/admin/'+user.id+'/'+1
            });
          }
        })
      }
      next();
    }else {


      if(to.path === '/'){
        next();
      }else {
        alert('请先进行登录！')
        next({
          path:'/'
        })
      }
    }
  }
  else {
    next();
  }
  /*如果本地 存在 token 则 不允许直接跳转到 登录页面*/
  if(to.fullPath == "/"){
    if(localStorage.getItem('user')){
      let user = localStorage.getItem('user')? JSON.parse(localStorage.getItem('user')):null
      next({
        path:'/admin/'+user.id+'/'+1
      });
    }else {
      next();
    }
  }
});
export default router
